<template>
  <div>
    <el-card class="box-card">
      <h2>编辑角色</h2>
      <el-form :model="roleForm" label-width="120px">
        <el-form-item label="当前角色名称：">
          <el-input v-model="roleName" readonly></el-input>
        </el-form-item>
        <el-form-item label="修改角色名称：" required>
          <el-input v-model="roleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="修改角色描述：" required>
          <el-input v-model="roleForm.description"></el-input>
        </el-form-item>
        <template v-for="(group, index) in permissions" :key="index">
          <el-form-item :label="group.name">
            <el-checkbox-group v-model="roleForm.functions[group.name]">
              <el-checkbox
                v-for="permission in group.permissions"
                :key="permission.id"
                :label="permission.id"
              >
                {{ permission.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
           <el-button @click="resetForm('customerForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleForm: {
        name: '',
        description: '',
        functions: {}
      },
      roleName: '',
      permissions: [
        {
          name: '合同管理：',
          permissions: [
            { id: 'draft_contract', name: '起草合同' },
            { id: 'finalize_contract', name: '定稿合同' },
            { id: 'query_contract', name: '查询合同' },
            { id: 'delete_contract', name: '删除合同' }
          ]
        },
        {
          name: '流程管理：',
          permissions: [
            { id: 'counter_sign_contract', name: '会签合同' },
            { id: 'approve_contract', name: '审批合同' },
            { id: 'sign_contract', name: '签订合同' },
            { id: 'assign_counter_sign', name: '分配会签' },
            { id: 'assign_approve', name: '分配审批' },
            { id: 'assign_sign', name: '分配签订' },
            { id: 'query_process', name: '流程查询' }
          ]
        },
        {
          name: '用户管理：',
          permissions: [
            { id: 'add_user', name: '新增用户' },
            { id: 'edit_user', name: '编辑用户' },
            { id: 'query_user', name: '查询用户' },
            { id: 'delete_user', name: '删除用户' }
          ]
        },
        {
          name: '角色管理：',
          permissions: [
            { id: 'add_role', name: '新增角色' },
            { id: 'edit_role', name: '编辑角色' },
            { id: 'query_role', name: '查询角色' },
            { id: 'delete_role', name: '删除角色' }
          ]
        },
        {
          name: '功能操作：',
          permissions: [
            { id: 'add_function', name: '新增功能' },
            { id: 'edit_function', name: '编辑功能' },
            { id: 'query_function', name: '查询功能' },
            { id: 'delete_function', name: '删除功能' }
          ]
        },
        {
          name: '权限管理：',
          permissions: [
            { id: 'configure_permission', name: '配置权限' }
          ]
        },
        {
          name: '客户管理：',
          permissions: [
            { id: 'add_customer', name: '新增客户' },
            { id: 'edit_customer', name: '编辑客户' },
            { id: 'query_customer', name: '查询客户' },
            { id: 'delete_customer', name: '删除客户' }
          ]
        }
      ]
    };
  },
  created() {
    this.roleName = this.$route.params.roleName;
    this.fetchRoleDetailsByName(this.roleName);
  },
  methods: {
    fetchRoleDetailsByName(roleName) {
        this.axios.get(`/api/role/search?name=${roleName}`)
        .then(response => {
          console.log('Response:', response.data);
          const roleDetails = response.data.data;
           console.log('Response2:', response.data.data);
             if (roleDetails) {
               const role = roleDetails[0]; // 获取数组中的第一个元素

            this.roleForm = {
              name: role.name,
              description: role.description,
              functions: this.parseFunctions(role.functions)
            };
          }
        })
        .catch(error => {
          console.error('Error fetching role details:', error);
        });
    },
    parseFunctions(functionsString) {
      console.log('Functions:',functionsString); // 在这里添加打印语句
      const functionsArray = functionsString.split(',');
      const functions = {};
      this.permissions.forEach(group => {
        functions[group.name] = [];
        functionsArray.forEach(func => {
          if (group.permissions.some(permission => permission.id === func)) {
            functions[group.name].push(func);
          }
        });
      });
      return functions;
    },
    submitForm() {
      const functionsString = Object.values(this.roleForm.functions).flat().join(',');
      const updatedRole = {
        ...this.roleForm,
        functions: functionsString
      };
        console.log('Functions after stringify:', functionsString);
       console.log('Updated role:', updatedRole);  // 检查 updatedRole 对象
      this.axios.put(`/api/role/edit/${this.roleName}`, updatedRole)
        .then(() => {
          console.log('Role update successful');  // 检查请求成功响应
          this.$message({
            message: '角色更新成功',
            type: 'success'
          });
          this.$router.push('/list_role');
        })
        .catch(error => {
          console.error('Error updating role:', error);
          this.$message.error('角色更新失败');
        });
    },
        resetForm(formName) {
              // 重置表单数据和选中的角色
                 this.roleForm.name = '';
                 this.roleForm.description = '';
                 this.roleForm.functions = {};
                 this.selectedRole = null;
          }
  }
};
</script>

<style scoped>
.box-card {
  margin: auto;
  width: 600px;
}
.el-form-item {
  margin-bottom: 20px;
}
</style>
//todo重置